<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/5/11
 * Time: 18:29
 */
namespace app\api\controller\v1;
use think\Controller;
class Base extends Controller
{
    public $account = '';
    public function _initialize()
    {
        $arr = input('param.');
        //验证接口是否超时
//        $this->check_time($arr);
        //验证接口token
        $this->check_apitoken($arr);
//
    }

    //判断是否登录
    public function isLogin($arr) {
        $id = isset($arr['uid'])?$arr['uid']:null;
        $token = isset($arr['token'])?$arr['token']:null;
        if(empty($id) || empty($token)){
            return show(444,'请先登录');
        }
        $res = model('User')->field('token,expire_time')->where('id',$id)->find();
        if(empty($res['token'])){
            return show(444,'请先登录');
        }
        if(time()>$res['expire_time']){
            return show(444,'账号过期,请重新登录');
        }
        if($arr['token']!==$res['token']){
            return show(444,'参数有误，请重新登录');
        }
    }


    /**
     * 验证请求是否超时
     * @param  [array] $arr [包含时间戳的参数数组]
     * @return [json]      [检测结果]
     */

    public function check_time($arr) {
        if (!isset($arr['time']) || intval($arr['time']) <= 1) {
            return show(400, '时间戳不正确!');
        }
        if (time() - intval($arr['time']) > 30) {
            return show(400, '请求超时!');
        }
    }

    /**
     * @param $arr [包含token的数组]
     * @return json [Token是否正确]
     */
    public function check_apitoken($arr){
        if(!isset($arr['api_token'])){
            return show(400,'参数错误');
        }
        $apitoken = $this->makeToken($arr['time']);
        if($arr['api_token'] !== $apitoken){
            return show(444,'禁止访问');
        }

    }

    /**
     * @param $time [接收时间的数组]
     * @return string[服务器端生成的Token]
     */
    public function makeToken($time){
        $secret = config('secret.secret');
        $apitoken = sha1($secret.$time);
        return $apitoken;
    }
}